package com.example.mycardgame.model

import com.example.mycardgame.R

data class Card(
    val id: Int,
    val imageResId: Int,
    var isFaceUp: Boolean = false,
    var isMatched: Boolean = false
)

class CardGameModel {
    private val cardImageRes = listOf(
        R.drawable.card1, R.drawable.card2, R.drawable.card3,
        R.drawable.card4, R.drawable.card5, R.drawable.card6,
        R.drawable.card1, R.drawable.card2, R.drawable.card3,
        R.drawable.card4, R.drawable.card5, R.drawable.card6
    )

    lateinit var cards: MutableList<Card>
    internal val flippedCards = mutableListOf<Card>()

    fun initGame() {
        cards = cardImageRes.mapIndexed { index, resId ->
            Card(id = index, imageResId = resId)
        }.shuffled().toMutableList()
        flippedCards.clear()
    }

    fun onCardClick(clickedCard: Card): Boolean {
        if (clickedCard.isMatched || clickedCard.isFaceUp) return false

        clickedCard.isFaceUp = true
        flippedCards.add(clickedCard)

        if (flippedCards.size == 2) {
            val (first, second) = flippedCards
            if (first.imageResId == second.imageResId) {
                first.isMatched = true
                second.isMatched = true
                flippedCards.clear()
                return true
            }
            return false
        }
        return true
    }

    fun flipBackUnmatchedCards() {
        flippedCards.forEach { it.isFaceUp = false }
        flippedCards.clear()
    }

    fun isGameOver() = cards.all { it.isMatched }
    fun shouldFlipBack() = flippedCards.size == 2
}